// src/stores/themeStore.js
import { defineStore } from "pinia";
import { themes, defaultSettings } from "../assets/utils/custom-theme.js";
import Taro from "@tarojs/taro";

export const useThemeStore = defineStore("theme", {
  state: () => ({
    currentTheme: { ...defaultSettings },
    themeMode: "system", // light, dark, system
    fontSize: 14,
    enableAnimation: true,
  }),

  actions: {
    // 初始化主题
    initTheme() {
      // 获取系统信息
      try {
        const systemInfo = Taro.getSystemInfoSync();
        const isDark = systemInfo.theme === "dark";

        // 从本地存储加载主题设置
        const savedSettings = Taro.getStorageSync("themeSettings");
        if (savedSettings) {
          const settings = JSON.parse(savedSettings);
          this.themeMode = settings.mode || "system";
          this.fontSize = settings.size || 14;
          this.enableAnimation = settings.animation !== false;

          // 应用保存的主题色
          if (settings.color) {
            this.setTheme(settings.color);
          }
        }

        // 如果是系统模式，根据系统主题设置
        if (this.themeMode === "system") {
          this.applySystemTheme(isDark);
        } else {
          this.applyTheme();
        }

        // 监听系统主题变化
        Taro.onThemeChange((result) => {
          if (this.themeMode === "system") {
            this.applySystemTheme(result.theme === "dark");
          }
        });
      } catch (e) {
        console.error("初始化主题失败:", e);
      }
    },

    // 应用系统主题
    applySystemTheme(isDark) {
      if (isDark) {
        this.currentTheme = { ...this.currentTheme, ...themes.dark };
      } else {
        this.currentTheme = {
          ...defaultSettings,
          primaryColor: this.currentTheme.primaryColor,
          buttonPrimaryBackgroundColor: this.currentTheme.primaryColor,
          primaryColorEnd: this.currentTheme.primaryColor,
        };
      }
      this.applyTheme();
    },

    // 设置主题模式
    setThemeMode(mode) {
      this.themeMode = mode;
      if (mode === "system") {
        // 获取系统当前主题
        const systemInfo = Taro.getSystemInfoSync();
        this.applySystemTheme(systemInfo.theme === "dark");
      } else if (mode === "dark") {
        this.currentTheme = "dark";
      } else {
        // 恢复之前的浅色主题设置
        this.currentTheme = {
          ...defaultSettings,
          primaryColor: this.currentTheme.primaryColor,
          buttonPrimaryBackgroundColor: this.currentTheme.primaryColor,
          primaryColorEnd: this.currentTheme.primaryColor,
        };
      }
      this.saveSettings();
      this.applyTheme();

      // 更新 tabbar
      this.updateTabBar();
    },

    // 设置主题色
    setTheme(color) {
      this.currentTheme = {
        ...this.currentTheme,
        primaryColor: color,
        buttonPrimaryBackgroundColor: color,
        primaryColorEnd: color,
      };
      this.saveSettings();
      this.applyTheme();

      // 更新 tabbar
      this.updateTabBar();
    },

    // 更新 tabbar 样式
    updateTabBar() {
      if (typeof Taro.getTabBar === "function") {
        const tabBar = Taro.getTabBar();
        if (tabBar) {
          tabBar.$forceUpdate(); // 强制更新 tabbar
        }
      }
    },

    // 设置字体大小
    setFontSize(size) {
      this.fontSize = size;
      this.currentTheme.baseFontSize = `${size}px`;
      this.saveSettings();
      this.applyTheme();
    },

    // 设置动画
    setAnimation(enabled) {
      this.enableAnimation = enabled;
      this.currentTheme.enableAnimation = enabled;
      this.saveSettings();
      this.applyTheme();
    },

    // 根据预设用户主题设置
    setThemeByUser(userId) {
      if (themes[userId]) {
        this.currentTheme = { ...themes[userId] };
        this.saveSettings();
        this.applyTheme();
      }
    },

    // 重置为默认设置
    resetToDefault() {
      this.currentTheme = { ...defaultSettings };
      this.themeMode = "system";
      this.fontSize = 14;
      this.enableAnimation = true;
      this.saveSettings();
      this.applyTheme();
    },

    // 保存设置到本地存储
    saveSettings() {
      const settings = {
        mode: this.themeMode,
        color: this.currentTheme.primaryColor,
        size: this.fontSize,
        animation: this.enableAnimation,
      };
      Taro.setStorageSync("themeSettings", JSON.stringify(settings));
    },

    // 应用主题到DOM
    applyTheme() {
      // 设置主题模式
      document.documentElement.setAttribute("data-theme", this.themeMode);

      // 应用CSS变量
      const root = document.documentElement;
      Object.entries(this.currentTheme).forEach(([key, value]) => {
        const cssVar = `--${key.replace(/([A-Z])/g, "-$1").toLowerCase()}`;
        root.style.setProperty(cssVar, value);
      });
      console.log(root);

      // 应用字体大小
      root.style.setProperty("--base-font-size", `${this.fontSize}px`);

      // 应用动画设置
      root.style.setProperty(
        "--enable-animation",
        this.enableAnimation ? "1" : "0"
      );
    },
  },
});
